package com.cqhz.quwan.ui.activity

import android.content.Intent
import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.CodeBean
import com.cqhz.quwan.model.OrderBetInfoBean
import com.cqhz.quwan.model.OrderInfoBean
import com.cqhz.quwan.mvp.OrderDetailContract
import com.cqhz.quwan.mvp.OrderDetailPresenter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.util.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_order_detail.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject


/**
 * 足彩订单详情
 * Created by Guojing on 2018/11/29.
 */
class OrderDetailActivity : GoBackActivity(), OrderDetailContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var orderDetailPresenter: OrderDetailPresenter
    private var orderInfo: OrderInfoBean? = null
    private var orderId = ""
    private var playType = ""

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "订单详情"
    }

    override fun layout(): Int {
        return R.layout.activity_order_detail
    }

    override fun initView() {
        orderDetailPresenter.attachView(this)
        orderId = intent.getStringExtra(KeyContract.OrderId)
        orderDetailPresenter.getOrderDetail(orderId)
        if (APP.get()!!.loginInfo != null) {
            orderDetailPresenter.getCodeImg(APP.get()!!.loginInfo!!.userId!!)
        }
        setOnClick()
    }

    /**
     * 设置点击事件
     */
    private fun setOnClick() {
        setTitleBarRightText("截图") {
            val bitmap = getNestedScrollViewBitmap(sv_content)
            bitmap.saveImage("天天趣玩", "${System.currentTimeMillis()}.jpg") { it ->
                scanPhoto(it)
                showToast("保存成功: $it")
            }
        }
        action_cancel.setOnClickListener {
            orderDetailPresenter.updateOrderStatus(orderId, "7")// 取消订单
        }
        action_commit.setOnClickListener {
            val intent = Intent(this, GoPaymentActivity::class.java)
            intent.putExtra(KeyContract.Amount, orderInfo!!.payAmount?.toDouble())
            intent.putExtra(KeyContract.ActualAmount, orderInfo!!.payAmount?.toDouble())
            intent.putExtra(KeyContract.OrderId, orderInfo!!.id)
            intent.putExtra(KeyContract.LotteryName, "竞猜足球 $playType")
            startActivity(intent)
        }
    }

    /**
     * 初始化列表适配器
     */
    private fun initAdapter(orderBetInfoList: ArrayList<OrderBetInfoBean>) {
        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, rv_content.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        var orderListAdapter = CommonAdapterHelper.getOrderDetailListAdapter(this, orderBetInfoList, orderInfo!!.lotteryId)
        orderListAdapter.emptyView = emptyView

        // 当前页面列表适配器的事件
        rv_content.layoutManager = LinearLayoutManager(this) as RecyclerView.LayoutManager?
        rv_content.isNestedScrollingEnabled = false// 让NestedScrollView滑动顺滑
        rv_content.adapter = orderListAdapter
    }

    override fun setOrderDetail(bean: OrderInfoBean) {
        orderInfo = bean

        val orderBetInfoList = Gson().fromJson(bean.orderBetJson, object : TypeToken<List<OrderBetInfoBean>>() {}
                .type) as? MutableList<OrderBetInfoBean>

        when (bean.lotteryId) {
            "21" -> {
                iv_ball.setImageResource(R.drawable.order_logo_soccer)

                playType = if (orderBetInfoList == null) {
                    ""
                } else {
                    when (orderBetInfoList!![0].playType) {
                        1 -> "胜平负"
                        2 -> "让球胜平负"
                        3 -> "比分"
                        4 -> "总进球数"
                        5 -> "半全场"
                        6 -> "混合投注"
                        7 -> "单关固定"
                        8 -> "猜一场"
                        9 -> "2选1"
                        else -> "其他"
                    }
                }
            }
            "24" -> {
                iv_ball.setImageResource(R.mipmap.ic_logo_basketball)

                playType = if (orderBetInfoList == null) {
                    ""
                } else {
                    when (orderBetInfoList!![0].playType) {
                        1 -> "胜负"
                        2 -> "让分胜负"
                        3 -> "胜分差"
                        4 -> "大小分"
                        5 -> "混合过关"
                        6 -> "单关"
                        else -> "其他"
                    }
                }
                val width0 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                val width1 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                val width2 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                width0.weight = 1f
                width1.weight = 1f
                width2.weight = 1f
                tv_name.layoutParams = width0
                tv_content.layoutParams = width1
                tv_result.layoutParams = width2
            }
        }

        var orderStatus = ""
        ll_operation.visibility = View.GONE
        when (bean.status) {
            0, 1 -> {
                orderStatus = "待下单"
                ll_operation.visibility = View.VISIBLE
            }
            2 -> {
                orderStatus = "待开奖"
            }
            3 -> orderStatus = "未中奖"
            4 -> orderStatus = "已中奖"
            5 -> orderStatus = "待领奖"
            6 -> orderStatus = "已领奖"
            7 -> orderStatus = "已取消"
            9 -> orderStatus = "已下单"
            else -> orderStatus = "已失效"
        }
        tv_order_status.text = orderStatus
        when (bean.status) {
            4, 5, 6 -> {
                iv_prize.visibility = View.VISIBLE
                ll_profit.visibility = View.VISIBLE
                tv_commission_revenues.setTextColor(Color.parseColor("#ff0000"))
            }
            else -> {
                iv_prize.visibility = View.GONE
                ll_profit.visibility = View.GONE
                tv_commission_revenues.setTextColor(Color.parseColor("#333333"))
            }
        }
        tv_status.visibility = if (iv_prize.visibility == View.GONE) View.VISIBLE else View.GONE
        tv_status.text = when (bean.ticketStatus) {
            0 -> "待下单"
            1 -> "已下单"
            2 -> "已取消"
            else -> "已失效"
        }
        tv_game_type_title.text = when (bean.lotteryId) {
            "21" -> "竞猜足球"
            "24" -> "竞猜篮球"
            else -> "其他"
        }
        tv_game_name.text = playType
        if (bean.isBonusOptimize != 0) {
            tv_bonus_type.visibility = View.GONE
        } else {
            tv_bonus_type.visibility = View.VISIBLE
            tv_bonus_type.text = when (bean.bonusOptimizeType) {
                0 -> "平均优化"
                1 -> "博热优化"
                2 -> "博冷优化"
                else -> ""
            }
        }
        tv_amount_pay.text = bean.payAmount.formatNoZero()
        tv_amount_profit.text = bean.prize.formatNoZero()
        tv_amount_profit.setTextColor(Color.parseColor(if (bean.prize.toDouble() > 0) "#FF0000" else "#333333"))
        tv_prize.text = bean.expectedBonus + "趣豆"

        when (bean.followStatus) {
            1 -> {// 跟单
                ll_bg.visibility = View.VISIBLE
                ll_bet_info.visibility = View.GONE
                ll_follow.visibility = View.VISIBLE
                ll_security_setting.visibility = View.GONE
                ll_profit.visibility = View.GONE
                ll_commission_revenues.visibility = View.GONE
                ll_expert.visibility = View.VISIBLE

                ll_match.setBackgroundResource(R.drawable.sp_order_detail_bg0)
                tv_game_name.text = bean.pushOrderDetailVO.betType
                tv_follow_number.text = bean.pushOrderDetailVO.follows.toString() + "人"// 跟单人数
                tv_follow_amount.text = bean.pushOrderDetailVO.followAmt.toString()// 跟单额
                tv_commission_rate.text = bean.pushOrderDetailVO.commissionRate.formatNoZero() + "%"// 佣金比例
                tv_security_setting.text = when (bean.pushOrderDetailVO.openStatus) {
                    0 -> "开赛后公开"
                    1 -> "开奖后公开"
                    2 -> "保密"
                    else -> "保密"
                }// 保密设置
                tv_expert.text = bean.pushOrderDetailVO.expertName// 专家
                if (orderBetInfoList != null) {
                    ll_bg.visibility = View.GONE
                    initAdapter(orderBetInfoList as ArrayList<OrderBetInfoBean>)
                }
            }
            2 -> {// 推单
                ll_bg.visibility = View.GONE
                ll_bet_info.visibility = View.VISIBLE
                ll_follow.visibility = View.VISIBLE
                ll_security_setting.visibility = View.VISIBLE
                ll_commission_revenues.visibility = View.VISIBLE
                ll_expert.visibility = View.GONE

                ll_match.setBackgroundResource(R.drawable.sp_order_detail_bg1)
                tv_game_name.text = bean.pushOrderDetailVO.betType
                // 投注信息
                tv_game_type.text = playType
                tv_bet_type.text = bean.betBunch.replace("-", "串")
                tv_bet_times.text = bean.betNum + "注"
                tv_bet_number.text = bean.betTimes + "倍"

                tv_follow_number.text = bean.pushOrderDetailVO.follows.toString() + "人"// 跟单人数
                tv_follow_amount.text = bean.pushOrderDetailVO.followAmt.toString()// 跟单额
                tv_commission_rate.text = bean.pushOrderDetailVO.commissionRate.formatNoZero() + "%"// 佣金比例
                tv_security_setting2.text = when (bean.pushOrderDetailVO.openStatus) {
                    0 -> "开赛后公开"
                    1 -> "开奖后公开"
                    2 -> "保密"
                    else -> "保密"
                }// 保密设置
                tv_profit.text = bean.pushOrderDetailVO.profitOdds + "%"// 盈利率
                tv_commission_revenues.text = bean.pushOrderDetailVO.commission// 佣金收益
                initAdapter(orderBetInfoList as ArrayList<OrderBetInfoBean>)
            }
            else -> {// 普通订单
                ll_bg.visibility = View.GONE
                ll_bet_info.visibility = View.VISIBLE
                ll_follow.visibility = View.GONE

                ll_match.setBackgroundResource(R.drawable.sp_order_detail_bg1)
                // 投注信息
                tv_game_type.text = playType
                tv_bet_type.text = bean.betBunch.replace("-", "串")
                tv_bet_times.text = bean.betNum + "注"
                tv_bet_number.text = bean.betTimes + "倍"
                initAdapter(orderBetInfoList as ArrayList<OrderBetInfoBean>)
            }
        }
        if ((bean.status == 0 || bean.status == 1) && bean.followStatus != 1) {
            ll_prize.visibility = View.VISIBLE
        } else {
            ll_prize.visibility = View.GONE
        }
        tv_time.text = "下单时间：" + bean.createTime
    }

    override fun setCodeImg(bean: CodeBean) {
        iv_code.setLoadImage(this, bean.image, 0)
    }

    override fun updateSuccess() {
        showToast("取消成功")
        orderDetailPresenter.getOrderDetail(orderId)
    }

    override fun onResume() {
        super.onResume()
        orderDetailPresenter.getOrderDetail(orderId)
    }

    override fun onDestroy() {
        super.onDestroy()
        orderDetailPresenter.detachView()
    }
}
